package cn.j229.bug.zhongxuan.hualian.controller;

import cn.j229.bug.zhongxuan.hualian.exception.BusinessException;
import cn.j229.bug.zhongxuan.hualian.pojo.Admin;
import cn.j229.bug.zhongxuan.hualian.service.AdminService;
import cn.j229.bug.zhongxuan.hualian.utils.JsonResult;

import cn.j229.bug.zhongxuan.hualian.utils.MD5Util;
import cn.j229.bug.zhongxuan.hualian.utils.Salt;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author smile_ZhongXuan
 * @Date 2020/10/22 16:58
 * @Version 1.0
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    AdminService adminService = null;
    JsonResult jsonResult = new JsonResult();

    @PostMapping("/addAdmin")
    public Map addAdmin(@RequestBody Admin admin){
        Admin phoneByAdmin = adminService.findPhoneByAdmin(admin.getPhone());
        if(phoneByAdmin == null || phoneByAdmin.equals("")){
            String password1 = MD5Util.encode(admin.getPhone().substring(5, 11)).toUpperCase();
            String salt = Salt.createSalt();
            admin.setSalt(salt);
            admin.setPassword(Salt.md5Password(password1,salt));
            adminService.addAdmin(admin);
            jsonResult.setCode("200");
            jsonResult.setMsg("新增超级管理员账号成功。");
        }else{
            jsonResult.setCode("0");
            jsonResult.setMsg("该超级管理员已存在，请更换手机号后重试。");
            throw new BusinessException("该手机号在数据库中已存在，请更换手机号重试。");
        }
        return jsonResult.getValues();
    }

    @PostMapping("/login")
    public Map loginAdmin(@RequestParam("phone") String phone){
        Admin phoneByAdmin = adminService.findPhoneByAdmin(phone);
        if(phoneByAdmin == null || phoneByAdmin.equals("")){
            jsonResult.setCode("0");
            jsonResult.setMsg("登录失败");
            throw new BusinessException("请检查手机号码是否在数据库中存在。");
        }
        String md5Password = Salt.md5Password(MD5Util.encode(phone.substring(5, 11)).toUpperCase(), phoneByAdmin.getSalt());
        if(phoneByAdmin.getPassword().equals(md5Password) || phoneByAdmin.getPassword() == md5Password){
            jsonResult.setCode("200");
            jsonResult.setMsg("登录成功！");
        }
        return jsonResult.getValues();
    }
}
